<template>
  <div class="app-container">
    <!-- 顶部导航栏 -->
    <HeaderPanel title="需求申请单管理" subtitle="DEMAND REQUEST MANAGEMENT"/>

    <SearchPanel
        :field-map="fieldMap"
        :column-widths="columnWidths"
        :loading="loading"
        @search="handleSearch"
        @handlePreview="handlePreview"
        @handleAdd="handleAdd"
        ref="searchPanelRef"
        :data-source="tableData"
    />

    <DetailDrawer
        :visible="drawerVisible"
        :record="record"
        :mode="modeRef"
        @close="onDrawerClose"
    />
  </div>
</template>

<script setup lang="ts">
import HeaderPanel from '@/components/HeaderPanel.vue'
import SearchPanel from '@/components/SearchPanel.vue';
import DetailDrawer from "./DetailDrawer.vue";
import {computed, ref} from "vue";
import {message} from "ant-design-vue";
import {
  fieldMap,
  fetchRequirementDetail,
  fetchRequirementList, columnWidths,
} from './indexService.ts';

const drawerVisible = ref(false);
const onDrawerClose = () => {
  drawerVisible.value = false;
  handleSearch();
};
const searchPanelRef = ref();
const loading = ref(false);
const tableData = ref<any[]>([]);
const record=computed(() => previewData.value);
const modeRef = ref();

const handleSearch = async () => {
  try {
    loading.value = true;

    // 构建查询参数
    const searchParams = {
      dpmNameCn: searchPanelRef.value.formData.dpmNameCn.trim(),
      roleName: searchPanelRef.value.formData.roleName.trim(),
      businessName: searchPanelRef.value.formData.businessName.trim(),
      fmDesc: searchPanelRef.value.formData.fmDesc.trim(),
      cpSpec: searchPanelRef.value.formData.cpSpec.trim(),
      reactionPlanCn: searchPanelRef.value.formData.reactionPlanCn.trim(),
      value: searchPanelRef.value.formData.value.trim(),
      current: searchPanelRef.value.pagination.current,
      pageSize: searchPanelRef.value.pagination.pageSize,
    };

    tableData.value = await fetchRequirementList(searchParams);

  } catch (error) {
    tableData.value = [];
  } finally {
    loading.value = false;
  }
};

const previewLoading = ref(false);
const previewData = ref<any>();

const handleAdd = () => {
  modeRef.value='add';
  drawerVisible.value=true;
}
const handlePreview = async () => {
  if (!searchPanelRef.value.selectedRowKey) {
    message.warning('请先选择一条记录进行预览');
    return;
  }

  try {
    modeRef.value = 'preview';
    previewLoading.value = true;
    previewData.value = null; // 先清空数据

    previewData.value = await fetchRequirementDetail(searchPanelRef.value.selectedRowKey);
    drawerVisible.value = true;
  } catch (error) {
    // 错误已经在服务函数中处理了
  } finally {
    previewLoading.value = false;
  }
};
</script>

<style scoped>
.app-container {
  background: linear-gradient(135deg, rgba(28, 32, 46, 0.95) 0%, #1e293b 100%);
  min-height: 100vh;
  font-family: 'Segoe UI', 'PingFang SC', 'Microsoft YaHei', sans-serif;
}
</style>